import Vue from 'vue'
import Vuex from 'vuex'
import * as types from './mutation-types'
import axios from '../config/axiosConfig'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        user: {
            store: '',
            name: '',
            role: ''
        },
        categoryDNList: [],
        departmentList: []
    },
    getters: {
        user(state) {
            return state.user
        },
        categoryDNList(state) {
            return state.categoryDNList
        },
        departmentList(state) {
            return state.departmentList
        }
    },
    mutations: {
        [types.LOGIN](state, payload) {
            Object.assign(state.user, payload)
            sessionStorage.setItem('role', payload.role)
        },
        [types.LOGOUT](state) {
            state.user.store = ''
            state.user.name = ''
            state.user.role = ''
        },
        [types.UPDATE_NAME](state, name) {
            state.user.name = name
        },
        [types.UPDATE_STORE](state, store) {
            state.user.store = store
        },
        [types.FETCH_CATEGORY_DN_LIST](state, categoryDNList) {
            state.categoryDNList = categoryDNList
        },
        [types.FETCH_DEPARTMENT_LIST](state, departmentList) {
            state.departmentList = departmentList
        }
    },
    actions: {
        async login({ commit }, payload) {
            commit(types.LOGIN, payload)
            const [categoryListRes, departmentListRes] = await Promise.all([axios.get('/categoryDNList'), axios.get('/departmentList')])
            if (categoryListRes && categoryListRes.code === 0) {
                commit(types.FETCH_CATEGORY_DN_LIST, categoryListRes.returnObject)
            }
            if (departmentListRes && departmentListRes.code === 0) {
                commit(types.FETCH_DEPARTMENT_LIST, departmentListRes.returnObject)
            }
        },
        logout({ commit }) {
            sessionStorage.removeItem('store')
            sessionStorage.removeItem('role')
            commit(types.LOGOUT)
        },
        updateName({ commit }, name) {
            commit(types.UPDATE_NAME, name)
        },
        updateStore({ commit }, store) {
            commit(types.UPDATE_STORE, store)
        }
    }
})

export default store
